// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// g [author] rhyme_lph
// H [email]  rhymelph@gmail.com
// R [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/entities/bank_detail_record_item_entity.dart';
import 'package:finance_app/src/entities/bank_reconciliation_record_entity.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/language_utils.dart';
import 'package:finance_app/src/widgets/button/normal_float_text_button.dart';
import 'package:finance_app/src/widgets/common/normal_table_pro.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/form/add_form.dart';
import 'package:finance_app/src/widgets/form/down_button_form.dart';
import 'package:finance_app/src/widgets/list_item/reconcile_top_list_item.dart';
import 'package:finance_app/src/widgets/select/reconcile_radio.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/all_reports/bank_reconciliation/reconcile_account_record_detail_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:tuple/tuple.dart';

export 'package:finance_app/src/entities/bank_reconciliation_record_entity.dart';

@RouterMeta(paramName: "reconcileAccountRecordDetailPage")
class ReconcileAccountRecordDetailPage extends StatefulWidget {
  final String title;
  final BankReconciliationRecordEntity bank;
  final int bankId;

  const ReconcileAccountRecordDetailPage(
      {Key key, this.title, this.bank, this.bankId})
      : super(key: key);

  @override
  _ReconcileAccountRecordDetailPageState createState() =>
      _ReconcileAccountRecordDetailPageState();
}

class _ReconcileAccountRecordDetailPageState
    extends State<ReconcileAccountRecordDetailPage>
    with
        PagePresenter<ReconcileAccountRecordDetailPage,
            ReconcileAccountRecordDetailProvider> {
  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
        title: widget.title,
      );

  @override
  void initState() {
    provider.id = widget.bank.id;
    provider.bankId = widget.bankId;
    provider.realDifference = widget.bank.total;
    super.initState();
  }

  @override
  Widget get buildLoadingWidget => Stack(
        children: [
          _buildRecordList(
            child: super.buildLoadingWidget,
          ),
          _buildBottomBar(),
        ],
      );

  @override
  Widget get buildEmptyWidget => Stack(
        children: [
          _buildRecordList(
            child: super.buildEmptyWidget,
          ),
          _buildBottomBar(),
        ],
      );

  @override
  Widget get buildWidget => Stack(
        children: [
          _buildRecordList(
            child: listBuilder<List<BankDetailRecordItemEntity>>(
              selector: (_, __) => List.from(__.data),
              builder: (BuildContext context,
                      List<BankDetailRecordItemEntity> value, Widget child) =>
                  ListView.builder(
                      itemBuilder: _buildItems, itemCount: value.length),
            ),
          ),
          _buildBottomBar(),
        ],
      );

  ColoredBox _buildRecordList({Widget child}) {
    return ColoredBox(
      color: Colors.white,
      child: Column(
        children: [
          _buildTopWidget(),
          Expanded(child: child),
        ],
      ),
    );
  }

  Widget _buildBottomBar() => Positioned(
        bottom: getDp(32) + MediaQuery.of(context).padding.bottom,
        left: 0.0,
        right: 0.0,
        child: Center(
            child: listBuilder<bool>(
          selector: (_, __) => __.difference == 0,
          builder: (BuildContext context, bool value, Widget child) =>
              NormalFloatTextButton(
            title: S.current.match,
            onTap: value == true ? provider.onMatch : null,
          ),
        )),
      );

  Widget _buildTopWidget() => Column(
        children: [
          NormalTableProTitleItem(
            title: S.current.bank_records,
            padding: EdgeInsets.symmetric(
              horizontal: getDp(25),
              vertical: getDp(5),
            ),
          ),
          ReconcileTopListItem(
            onTap: () {},
            name: widget.bank.bankTransactionName,
            code: widget.bank.bankTransactionNumber,
            datetime:
                DateTimeUtils.formatDateTimeString(widget.bank.createdAt, true),
            status: S.current.unmatched,
            amount: widget.bank.total,
          ),
          NormalTableProTitleItem(
            title: S.current.book_records,
            padding: EdgeInsets.symmetric(
              horizontal: getDp(25),
              vertical: getDp(5),
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              listBuilder<String>(
                selector: (_, __) => __.showStatus,
                builder: (BuildContext context, String value, Widget child) =>
                    Padding(
                  padding: EdgeInsets.only(left: getDp(5)),
                  child: DownButtonForm(
                    title: LanguageUtils.translateStatus(value),
                    onTap: provider.onChangeStatus,
                  ),
                ),
              ),
              AddForm(
                title: S.current.add_new,
                onTap: provider.onAddNew,
              ),
            ],
          ),
          AppSpaces.grayH05,
        ],
      );

  Widget _buildItems(BuildContext context, int index) {
    return listBuilder<Tuple2<bool, BankDetailRecordItemEntity>>(
      selector: (_, __) => Tuple2(
          __.selectReconcileList.firstWhere(
                  (element) => element.id == __.data[index].id,
                  orElse: () => null) !=
              null,
          __.data[index]),
      builder: (BuildContext context,
              Tuple2<bool, BankDetailRecordItemEntity> value, Widget child) =>
          PressedOpacityButton(
        onPressed: () => value.item2.bankReconciliationRecordId == null
            ? provider.onSelectReconcile(value.item2)
            : () {},
        child: ReconcileCheckBox(
          isSelect:
              value.item1 || value.item2.bankReconciliationRecordId != null,
          name: value.item2.name,
          code: value.item2.account.accountNumber,
          type: value.item2.flowType,
          isEnable: value.item2.bankReconciliationRecordId == null,
          datetime:
              DateTimeUtils.formatDateTimeString(value.item2.issuedAt, true),
          amount: value.item2.total,
        ),
      ),
    );
  }
}
